<template>
  <div v-loading="pageLoading" class="app-container flex-col">
    <div style="padding: 15px;">
      <el-row :gutter="30">
        <el-col :span="12">
          <el-form inline>
            <div class="flex flex-center">
              <label>线别</label>
              <el-select class="ml-15 flex1" v-model="initData.line" placeholder="请选择" @change="lineChange">
                <el-option v-for="l in lineOptions" :key="l.id" :value="l.id" :label="l.line_name"></el-option>
              </el-select>
              <label class="ml-15">工单</label>
              <el-select class="ml-15 flex1" v-model="initData.mo" filterable remote :remote-method="getGdOptions"
                @change="moChange">
                <el-option v-for="(g,t) in moOptions" :key="t" :value="g" :label="g"></el-option>
              </el-select>
            </div>
          </el-form>
        </el-col>
        <el-col :span="12">
          <emp-scan :focus.sync="empFocus" :data="initData" @onClear="checkData" @onChange="checkData">
          </emp-scan>
        </el-col>
      </el-row>
    </div>
    <div class="p-15 z-border-t flex flex-center">
      <label>设置自动拼板数量</label>
      <el-input-number class="ml-20" :min="2" v-model="initData.puzzleNum" @change='puzzleNumChange' ref="puzzleNum">
      </el-input-number>
      <label class="ml-60">请扫码</label>
      <el-input class="ml-15 flex1 z-scan t-34" v-model="scanData" ref="scan" :disabled="!canScan"
        @keyup.enter.native="afterScan">
      </el-input>
    </div>
    <div class="flex1 flex z-border-t" style="overflow-x: hidden; overflow-y: auto;">
      <div class="z-panel p-15 z-border-r" style="width: 30%;">
        <div class="z-panel-title">工单信息</div>
        <div class="z-panel-body" v-if="!!moInfo.mo_no">
          <div class="z-info-item">
            <div class="z-info-label">工单单号</div>
            <div class="z-info-value">{{moInfo.mo_no}}</div>
          </div>
          <div class="z-info-item">
            <div class="z-info-label">产品编号</div>
            <div class="z-info-value">{{moInfo.key_part_no}}</div>
          </div>
          <div class="z-info-item">
            <div class="z-info-label">产品名称</div>
            <div class="z-info-value">{{moInfo.key_part_name}}</div>
          </div>
          <div class="z-info-item">
            <div class="z-info-label">客户代码</div>
            <div class="z-info-value">{{moInfo.cust_code}}</div>
          </div>
          <div class="z-info-item">
            <div class="z-info-label">客户名称</div>
            <div class="z-info-value">{{moInfo.cust_name}}</div>
          </div>
          <div class="z-info-item">
            <div class="z-info-label">工单目标数量</div>
            <div class="z-info-value">{{moInfo.target_qty}}</div>
          </div>
          <div class="z-info-item">
            <div class="z-info-label">投入/产出</div>
            <div class="z-info-value">{{moInfo.input_qty}}/{{moInfo.output_qty}}</div>
          </div>
        </div>
      </div>
      <div class="z-panel flex1 p-15 z-border-r">
        <div class="flex" style="margin: 0 auto 20px">
          <div class="z-panel-title mr-30">已扫/总数 &nbsp;&nbsp;
            {{snHisIndex}} / {{ snHistory.length }}
          </div>
          <el-button type="info" size="medium" @click='bindSSN' v-if="!!snHisIndex">拼板
          </el-button>
        </div>
        <div class="z-panel-body">
          <div class="flex flexW">
            <div class="mr-30 mb-30 z-border" v-for="(i,t) in snHistory" :key="t">
              <div class="p-10 z-border-b text-blue">{{i.serial_number}}</div>
              <div v-if="!!i.shipping_sn" class="p-10 text-green">{{i.shipping_sn}}</div>
              <div v-else class="p-10 text-gray">待扫描</div>
            </div>
          </div>
          <div class="z-border z-empty-box" v-show="!snHistory.length">暂无数据</div>
        </div>
      </div>
    </div>
    <message-box :msgs="msgs"></message-box>
  </div>
</template>
<script>
import dayjs from 'dayjs'
import _ from 'lodash'
import empScan from '@/components/WinClient/empScan'
import messageBox from '@/components/WinClient/messageBox'
import mixinClient from '@/views/_common/mixinClient'
export default {
  mixins: [mixinClient],
  components: { empScan, messageBox },
  name: 'smtBindSSN',
  data() {
    return {
      pageLoading: false,
      scanData: null,
      empFocus: false,
      initData: {
        puzzleNum: 0,
        mo: null,
        emp: null,
        empName: null,
        line: null,
      },
      lineOptions: [],
      moOptions: [],
      snHistory: [],
      msgs: [],
      moInfo: {},
      sixRules: null,
    }
  },
  computed: {
    snHisIndex() {
      return this.snHistory.filter((x) => !!x.shipping_sn).length
    },
    canScan() {
      return this.initData.emp && this.initData.line && this.initData.mo
    },
  },
  methods: {
    // 获取前六位编码规则
    getSixRules() {
      this.$request(this.$api.param + 'getbyname?name=' + 'PcbSsn' + '&type=' + 'SN_SPLIT_RULE', {}, 'get').then(
        (r) => {
          this.sixRules = r[0].param_value
        },
      )
    },
    // 校验前六位
    checkSSN(sn) {
      return this.$request(this.$api.snsplitrule + 'splitSn?rule=' + this.sixRules + '&sn=' + sn, {}, 'get', true)
    },
    checkData() {
      if (!this.initData.mo) {
        this.showMessage('请选择线别和工单')
        return
      }
      if (!this.initData.emp) {
        this.showMessage('请扫描作业员')
        this.empFocus = true
        return
      }
      if (this.initData.emp && !this.initData.empName) {
        this.showMessage('作业员不正确', true)
        return
      }
      if (!this.initData.puzzleNum) {
        this.showMessage('请先设置自动拼板数量', false)
        this.$refs.puzzleNum.select()
        return
      }
      this.getBindList()
      setTimeout(() => {
        this.showMessage('请扫描序号', false)
        this.$refs.scan.focus()
      }, 200)
    },
    setLocaSt() {
      localStorage.setItem(
        `${this.functionName}-initData`,
        JSON.stringify({ line: this.initData.line, mo: this.initData.mo, puzzleNum: this.initData.puzzleNum }),
      )
    },
    getLocaSt() {
      var tmp = localStorage.getItem(`${this.functionName}-initData`)
      if (tmp) {
        var tmpObj = JSON.parse(tmp)
        this.initData = Object.assign({}, this.initData, tmpObj)
        this.getGdOptions()
        this.getGdInfo()
        this.checkData()
      }
    },
    getLineOptions() {
      this.$request(this.$api.line + 'getlistbypage', { size: 999, page: 1 }, 'get', true)
        .then((r) => {
          this.lineOptions = r.list
        })
        .catch((e) => {
          this.showMessage(e.message, true)
        })
    },
    lineChange() {
      this.initData.mo = null
      this.moInfo = {}
      this.getGdOptions()
    },
    getGdOptions(value) {
      this.moOptions = []
      this.$request(this.$api.bindsn + 'MoQueryByLine', {
        lineid: this.initData.line,
        mo: value || '',
      }).then((r) => {
        this.moOptions = r
      })
    },
    moChange() {
      this.setLocaSt()
      this.getGdInfo()
      this.checkData()
    },
    puzzleNumChange() {
      this.setLocaSt()
      this.checkData()
    },
    // 根据工单查询
    getGdInfo() {
      this.$request(this.$api.mo + 'getinfo', { idOrNo: this.initData.mo }).then((r) => {
        this.moInfo = r
      })
    },
    // 根据工单查询待拼板
    getBindList() {
      this.pageLoading = true
      this.snHistory = []
      this.$request(
        this.$api.bindsn + 'GetUnBindSnList?mo=' + this.initData.mo + '&bindCount=' + this.initData.puzzleNum,
        {},
        'get',
        true,
      )
        .then((r) => {
          this.pageLoading = false
          if (!r.length) {
            this.showMessage(`${this.initData.mo} 该工单无拼板数据，请切换`, true)
            return
          }
          this.snHistory = r.map((i) => {
            return {
              id: i.id,
              serial_number: i.serial_number,
              shipping_sn: '',
              create_user: this.initData.emp,
              line_id: this.initData.line,
            }
          })
        })
        .catch((e) => {
          setTimeout(() => {
            this.$refs.puzzleNum.select()
          }, 200)
          this.showMessage(e.message, true)
        })
    },
    async afterScan() {
      this.scanData = this.scanData.trim()
      if (!this.scanData) {
        this.showMessage('没有扫描到任何内容', true)
        return
      }
      if (this.scanData.toUpperCase() == 'UNDO') {
        this.undo()
        return
      }
      let checkSix = await this.checkSSN(this.scanData)
        .then((r) => {
          return r.material
        })
        .catch((e) => {
          this.showMessage(e.message, true)
          setTimeout(() => {
            this.$refs.scan.select()
          }, 200)
          return
        })

      if (!checkSix) return
      if (!this.moInfo.key_part_no.includes(checkSix)) {
        this.showMessage(`[${this.scanData}] 条码与产品编号不一致`, true)
        setTimeout(() => {
          this.$refs.scan.select()
        }, 200)
        return
      }
      if (this.scanData.toUpperCase() == 'END') {
        if (this.snHistory.length >= 1) {
          this.bindSSN()
        } else {
          this.showMessage('拼版数量不能为0', true)
        }
        return
      }
      if (
        this.snHistory.length &&
        this.snHistory.some((i) => i.shipping_sn.toUpperCase() === this.scanData.toUpperCase())
      ) {
        this.showMessage('扫描SSN重复', true)
        setTimeout(() => {
          this.$refs.scan.select()
        }, 200)
        return
      }
      let data = {
        mo: this.initData.mo,
        line_id: this.initData.line,
        emp: this.initData.emp,
        ssn: this.scanData,
      }
      this.pageLoading = true
      this.$request(this.$api.bindsn + 'SSnCheck', data, 'post', true)
        .then((r) => {
          this.pageLoading = false
          if (r) {
            let tmp = this.snHistory.find((x) => !x.shipping_sn)
            tmp.shipping_sn = this.scanData
            this.scanData = null
            if (!this.snHistory.some((x) => !x.shipping_sn)) {
              setTimeout(() => {
                this.bindSSN('auto')
              }, 200)
            }
          } else {
            this.pageLoading = false
            setTimeout(() => {
              this.$refs.scan.select()
            }, 200)
            this.showMessage(e.message, true)
          }
        })
        .catch((e) => {
          this.pageLoading = false
          setTimeout(() => {
            this.$refs.scan.select()
          }, 200)
          this.showMessage(e.message, true)
        })
    },
    bindSSN(flag) {
      this.pageLoading = true
      let data = this.snHistory.filter((x) => flag == 'auto' || !!x.shipping_sn)
      this.$request(this.$api.bindsn + 'BindSSnCommit', data, 'post', true)
        .then((r) => {
          this.pageLoading = false
          if (r == '') {
            if (flag == 'auto') {
              this.showMessage('自动拼板成功，请继续扫描', false)
            } else {
              this.showMessage('拼板成功，请继续扫描', false)
            }
            this.scanData = null
            this.snHistory = []
            this.getBindList()
          } else {
            setTimeout(() => {
              this.$refs.scan.select()
            }, 200)
          }
        })
        .catch((e) => {
          this.pageLoading = false
          this.showMessage(e.message, true)
        })
    },
    undo() {
      this.scanData = null
      this.snHistory = []
      this.snHisIndex = 0
      this.showMessage('重置OK，请重新扫描', false)
      this.getBindList()
    },
  },
  mounted() {
    this.getLocaSt()
    this.getLineOptions()
    this.getSixRules()
  },
}
</script>
<style lang="scss" scoped>
@import '@/styles/client.scss';
</style>